
import { _decorator, Button, easing, EditBox, Label, Node, Rect, tween, Vec3 } from 'cc';
import { BaseUI } from '../../framework/base/BaseUI';
import { AudioMgr } from '../../framework/manager/AudioMgr';
import { EventMgr } from '../../framework/manager/EventMgr';
import { SDKMgr } from '../../framework/manager/SDKMgr';
import { UIMgr } from '../../framework/manager/UIMgr';
import { TimeUtils } from '../../framework/utils/TimeUtils';
import { AudioId, EventName, GameConfig, UIID } from '../config/Config';
import { GameDef } from '../gameLogic/GameDef';
import { PlayerMgr } from '../manager/PlayerMgr';
const { ccclass, property } = _decorator;

@ccclass('UIHome')
export class UIHome extends BaseUI {
    private powerOldPos: Vec3 = null;
    public powerTimer: Node;
    protected onLoad(): void {
        UIMgr.getInstance().getChildByName("UILoading").active = false
    }
    protected start() {
        console.log("UIHome start");
        this.findChilds("simpleModeBtn").onClick(this.onStratGame, this, 0);
        this.findChilds("hardModeBtn").onClick(this.onStratGame, this, 1);
        this.findChilds("hellModeBtn").onClick(this.onStratGame, this, 2);
        this.findChilds("settingBtn").onClick(this.onSetting, this);
        this.findChilds("btnRolue").onClick(this.onBtnRolue, this);
        this.findChilds("btnRank").onClick(this.onOpenRank, this);
        this.findChilds("practiceBtn").onClick(this.onStratGame, this, 0);
        this.findChilds("btnDayGit").onClick(this.onOpenDayGit, this);
        // this.findChilds("btnFankui").onClick(this.onFanKui, this);
        this.findChilds("getPowerBtn").onClick(this.onGetPowerBtn, this);
        this.powerOldPos = this.findChilds("flyIcon").position.clone();
        this.powerTimer = this.findChilds("powerTimer");
        this.timerUpdate(PlayerMgr.instance.userData.data.addHpEndTime);
        EventMgr.getInstance().on(EventName.UpdateHpTimer, this, this.timerUpdate);
        EventMgr.getInstance().on(EventName.RefreshHP, this, this.onRefreshHP);
        EventMgr.getInstance().on(EventName.UnlimitedHp, this, this.onReUnlimitedHP);
        this.onRefreshHP(PlayerMgr.instance.userData.data.roleHp, 1);
        this.refreshBtns();
        PlayerMgr.instance.checkDailyReset()
        this.showGuide()
        this.onFanKui()
        AudioMgr.getInstance().playMusic(AudioId.mainBgm, "MainBGM");
        this.findChilds("flyIcon").setWorldPosition(this.findChilds("tili_1").getWorldPosition());
        this.findChilds("levelLabeTip").getComponent(Label).string = `第 ${PlayerMgr.instance.userData.getLevel(0)} 关`
    }
    public editBox(type: number) {
        if (GameConfig.isGM) {
            let allCount = Number(this.findChilds("EditBox4").getComponent(EditBox).string);
            GameDef.instance.siamese[type] = Number(this.findChilds("EditBox1").getComponent(EditBox).string) || [3, 6, 9][type];
            GameDef.instance.siameseRandom = Number(this.findChilds("EditBox2").getComponent(EditBox).string) || 0.1;
            GameDef.instance.CBlockRate = Number(this.findChilds("EditBox3").getComponent(EditBox).string) || (0.6 + Math.random() * 0.3);
            if (allCount) {
                GameDef.instance.clockBlockType[type] = Array.from({ length: allCount + 1 }, (_, index) => index);
            }
        }
    }
    refreshBtns() {
        let index1 = PlayerMgr.instance.unlockLevel(1) ? 0 : 1;
        let index2 = PlayerMgr.instance.unlockLevel(2) ? 0 : 1;
        this.findChilds("hardModeBtn").children[index1].active = true;
        this.findChilds("hellModeBtn").children[index2].active = true
    }
    onStratGame(type: number, e: Button) {
        if (!PlayerMgr.instance.unlockLevel(type) && type != 3) {
            if (type == 1) {
                UIMgr.instance.showTip("请先通关青铜段位")
            }
            else if (type == 2) {
                UIMgr.instance.showTip("请先通关白银段位")
            }
            else if (type == 3) {
                UIMgr.instance.showTip("请先通关白银段位11")
            }
            return;
        }
        if (PlayerMgr.instance.userData.data.roleHp <= 0 && !PlayerMgr.instance.isUnlimitedHp()) {
            UIMgr.instance.openUI(UIID.UIPower, UIID.Default, 1, "体力恢复")
            return;
        }
        if (!PlayerMgr.instance.isNewGuide) {
            PlayerMgr.instance.userData.addRoleHp(-1)
        }
        console.warn("type", type, e.node.getChildByName("powerIcon"));
        this.editBox(type)
        if (e.target.getChildByName("powerIcon")) {
            tween(this.findChilds("flyIcon"))
                .to(0.8, { worldPosition: e.target.getChildByName("powerIcon").getWorldPosition() }, { easing: easing.circOut }).call(() => {
                    this.findChilds("flyIcon").setWorldPosition(this.findChilds("tili_1").getWorldPosition());
                    UIMgr.instance.openUI(UIID.UIGame, UIID.Default, type)
                    this.closeUI()
                })
                .start()
        } else {
            UIMgr.instance.openUI(UIID.UIGame, UIID.Default, type)
            this.closeUI()
        }
        SDKMgr.getInstance().reportEvent("enterstage", {
            "level_type": "主线",
            "stage": `第${GameDef.instance.curLevel}关`
        })
    }
    timerUpdate(dt: number) {
        if (PlayerMgr.instance.isMaxHp || PlayerMgr.instance.isUnlimitedHp()) {
            PlayerMgr.instance.reSetAddHpTimer();
            this.powerTimer.active = false;
            if (!PlayerMgr.instance.isUnlimitedHp()) {
                this.findChilds("currPower").getComponent(Label).string = "已满";
            }
        }
        if (dt === 0) {
            this.powerTimer.active = false;
            return;
        }
        // 不足10秒，前面补0 

        this.powerTimer.getComponent(Label).string = TimeUtils.SecondToHours(dt, false)
    }
    showGuide() {
        let guideData = PlayerMgr.getInstance().getGuideData();
        if (!guideData.isGuideEnd()) {
            if (guideData.currentId == 1) { //4
                guideData.addCurrentId(false)
                this.onStratGame(0, this.findChilds("practiceBtn").getComponent(Button))
            }
        }
    }
    onRefreshHP(value1, value2) {
        if (!PlayerMgr.instance.isUnlimitedHp()) {
            this.findChilds("currPower").getComponent(Label).string = "" + value1 + "/5";
        }
    }
    onReUnlimitedHP(isUnlimited: boolean, viodeNumber: number) {
        if (isUnlimited) {
            this.findChilds("currPower").getComponent(Label).string = "无限体力";
        }
        console.warn("onReUnlimitedHP", isUnlimited, viodeNumber);
    }
    onGetPowerBtn() {
        if (PlayerMgr.instance.isUnlimitedHp()) {
            UIMgr.instance.showTip("当前为无限体力状态")
            return;
        }
        UIMgr.instance.openUI(UIID.UIPower, UIID.Default, 2, "体力恢复")
    }
    onOpenPeacice() {
        // UIMgr.instance.openUI(UIID.UIDayGit,UIID.Default,true,"练习模式")
    }
    onOpenDayGit() {
        UIMgr.instance.openUI(UIID.UIDayGit, UIID.Default)
    }
    btnFanKuiWx: wx.FeedbackButton
    onFanKui() {
        let pos = this.findChilds("btnFankui").getWorldPosition();
        let rect = new Rect(pos.x, pos.y, 79, 79)
        this.btnFanKuiWx = SDKMgr.getInstance().createFeedbackButton(rect)
    }
    onClickToggle(e, data) {
        GameDef.instance.gameSkin = data;
        console.warn("onClickToggle", e, data);
    }
    onSetting() {
        UIMgr.instance.openUI(UIID.UISetting, UIID.Default, true, "设置")
    }
    onBtnRolue() {
        UIMgr.instance.openUI(UIID.UIRolue, UIID.Default)
    }
    onOpenRank() {
        UIMgr.instance.openUI(UIID.UIRank, UIID.Default, true, "排行榜")
    }
    protected onDisable(): void {
        EventMgr.getInstance().off(EventName.UpdateHpTimer, this, this.timerUpdate)
        EventMgr.getInstance().off(EventName.RefreshHP, this, this.onRefreshHP)
        EventMgr.getInstance().off(EventName.UnlimitedHp, this, this.onReUnlimitedHP);
        this.btnFanKuiWx && this.btnFanKuiWx.destroy()
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
